package io.wit.config;

import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 代码的执行流程preHandle->isAccessAllowed->isLoginAttempt->executeLogin
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2020/4/18 8:39
 * @QQ号码 444141300
 * @Email service@yinlz.com
 * @官网 <url>http://www.yinlz.com</url>
*/
public class JwtFilter extends BasicHttpAuthenticationFilter{

    @Override
    protected boolean preHandle(final ServletRequest req,final ServletResponse res) throws Exception {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        req.setCharacterEncoding("UTF-8");
        response.setHeader("Access-control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers",request.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())){
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(req,res);
    }

    /**
     * 2.执行带token认证有效,在此处理token是否需要更换!!!
     * @param request ServletRequest
     * @param response ServletResponse
     * @param mappedValue mappedValue
     * @return 是否成功
     */
    @Override
    protected boolean isAccessAllowed(final ServletRequest request,final ServletResponse response,final Object mappedValue) {
        final HttpServletRequest req = (HttpServletRequest) request;
        return true;
    }

    /**
     * ３.执行登录,在此处理token是否需要更换
    */
    @Override
    protected boolean executeLogin(final ServletRequest request,final ServletResponse response){
        final HttpServletRequest req = (HttpServletRequest) request;
        return true;
    }

    @Override
    public void afterCompletion(final ServletRequest request,final ServletResponse response,final Exception exception) throws Exception{
        super.afterCompletion(request,response,exception);
    }
}